package com.shujia.core

import java.util.Properties

import org.apache.flink.api.common.eventtime.WatermarkStrategy
import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.connector.base.DeliveryGuarantee
import org.apache.flink.connector.kafka.sink.{KafkaRecordSerializationSchema, KafkaSink}
import org.apache.flink.connector.kafka.source.KafkaSource
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer
import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.scala._

object Demo10KafkaSInkExactlyOnce {
  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment



    // 每 1000ms 开始一次 checkpoint
    env.enableCheckpointing(20000)

    // 高级选项：

    // 设置模式为精确一次 (这是默认值)
    env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

    // 确认 checkpoints 之间的时间会进行 500 ms
    env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

    // Checkpoint 必须在一分钟内完成，否则就会被抛弃
    env.getCheckpointConfig.setCheckpointTimeout(60000)

    // 允许两个连续的 checkpoint 错误
    env.getCheckpointConfig.setTolerableCheckpointFailureNumber(2)

    // 同一时间只允许一个 checkpoint 进行
    env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)

    // 使用 externalized checkpoints，这样 checkpoint 在作业取消后仍就会被保留
    env.getCheckpointConfig.setExternalizedCheckpointCleanup(
      ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)


    /**
      * 设置checkpoint保存数据方式和位置
      *
      */
    //老版本
    //env.setStateBackend(new RocksDBStateBackend("hdfs://master:9000/flink/checkpoint/"))

    //新版本
    //rocksDB状态后端
    env.setStateBackend(new EmbeddedRocksDBStateBackend(true))
    //env.setStateBackend(new HashMapStateBackend())
    env.getCheckpointConfig.setCheckpointStorage("hdfs://master:9000/flink/checkpoint/")





    //1、读取数据

    val source: KafkaSource[String] = KafkaSource.builder[String]
      .setBootstrapServers("master:9092")
      .setTopics("words")
      .setGroupId("my-group")
      .setStartingOffsets(OffsetsInitializer.earliest)
      .setValueOnlyDeserializer(new SimpleStringSchema()).build

    val linesDS: DataStream[String] = env.fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source")

    //1、统计单词的数量
    val wordsDS: DataStream[String] = linesDS.flatMap(_.split(","))

    /**
      * 将数据写入kafka中
      *
      */

    val properties = new Properties()
    properties.setProperty("transaction.timeout.ms", 10 * 60 * 1000 + "")

    val kafakSink: KafkaSink[String] = KafkaSink.builder()
      .setBootstrapServers("master:9092")
      .setRecordSerializer(KafkaRecordSerializationSchema.builder()
        .setTopic("kafka_sink")
        .setValueSerializationSchema(new SimpleStringSchema())
        .build()
      )
      //至少一次，如果任务失败重启会有重复数据，但是数据不会有延迟
      //      .setDeliverGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
      //唯一一次，任务失败重启数据也不会重复，但是数据会产生延迟，延迟的时间是checkpoint间隔时间
      //底层原理，将两次checkpoint中间的数据放到了一个事务中，要么都成功，要么都失败
      .setDeliverGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
      .setTransactionalIdPrefix("123")
      .setKafkaProducerConfig(properties)
      .build()

    wordsDS.sinkTo(kafakSink)

    //--isolation-level read_committed 读已提交
    //kafka-console-consumer.sh --bootstrap-server  master:9092 --from-beginning --isolation-level read_committed --topic kafka_sink


    env.execute()

  }

}
